<template>
  <div class="v-editor-track g-jc-sb">
    <div class="track-texts">
      <div
        v-for="item in texts"
        :key="item"
      >
        {{ item }}
      </div>
    </div>
    <div
      v-if="selected && !row.readonly && !isModelDisabled && !tableElementDisabled"
      class="g-pd-r-4 img-btn"
    >
      <img
        src="statics/icons/app/iconmore.png"
        class="g-pointer"
        @click="handleClick"
      />
    </div>
  </div>
</template>
<script lang="ts" setup>
import { PropertyRow } from "../../types";
import { Ref, ref, inject, watch, computed } from "vue";
import { trackEditorWindow } from "@/config/customSystemConfig/customWindows/trackEditor";
import { propertyUtil } from "../../PropertyUtil";
import { ModelData } from "@/constants/types";
import { modelService } from "@/modules/model/service";

const isModelDisabled = inject("isModelDisabled") as Ref<boolean>;

const props = defineProps<{
  row: PropertyRow;
  selected?: boolean;
  tableElementDisabled?: boolean;
  encrypted?: boolean;
}>();

const tracks = ref<Record<string, number>[]>([]);
const defaultTrack = ref<Record<string, number>>();

const trackPropertyMap = {
  "78900899730264832": {
    name: "经度",
    enName: "platLon",
    unit: "°"
  },
  "78900907976973952": {
    name: "纬度",
    enName: "platLat",
    unit: "°"
  },
  "78900923791613248": {
    name: "高度",
    enName: "platAlt",
    unit: "m"
  },
  "78900932849268224": {
    name: "速度",
    enName: "speed",
    unit: "m/s"
  }
};

const texts = computed(() => {
  const tracksEnNames: string[] = [];
  const enNameToValueMap: Record<string, any> = {};
  for (let key in trackPropertyMap) {
    const value = trackPropertyMap[key];
    tracksEnNames.push(value.enName);
    enNameToValueMap[value.enName] = value;
  }
  if (defaultTrack.value) {
    return tracksEnNames.map(
      enName => `${enNameToValueMap[enName].name}: ${defaultTrack.value?.[enName]}${enNameToValueMap[enName].unit};`
    );
  } else {
    return [];
  }
});

const getTracks = async () => {
  const trackIds: string[] = [];
  const trackIndexMap: Record<string, number> = {};
  const rowValue = props.row.value as ModelData[];
  rowValue.forEach((value, index) => {
    trackIds.push(value.id);
    trackIndexMap[value.id] = index;
  });
  const keys = Object.keys(trackPropertyMap);
  const instances = trackIds.map(id => {
    return {
      instanceId: id,
      keys
    };
  });
  const propertyValues = await modelService.getModelsPropertyValuesV2({ projectId: app.activeProject!.id, instances });
  propertyValues.sort((a, b) => trackIndexMap[a.instanceId] - trackIndexMap[b.instanceId]);
  const newTracks: Record<string, number>[] = [];
  propertyValues.forEach(({ properties, instanceId }) => {
    const obj: Record<string, number> = {};
    properties.forEach(item => {
      obj[trackPropertyMap[item.key].enName] = item.value as number;
    });
    obj.id = instanceId as any;
    newTracks.push(obj);
  });
  tracks.value = newTracks;
  defaultTrack.value = newTracks[0];
};

watch(() => props.row, getTracks, { immediate: true });

const handleClick = async () => {
  const data = JSON.stringify(tracks.value);
  let title = "";
  let attrType = "";
  const propertyKey = props.row.key;
  if (propertyKey === "78900938154478976") {
    title = "轨迹设置";
    attrType = "TrackEditor";
  } else if (propertyKey === "81437926063640704") {
    title = "任务区域";
    attrType = "TaskArea";
  }
  const res = await trackEditorWindow.popup({ data, title, attrType });
  if (res.success) {
    await propertyUtil.updatePropertyAndFresh(props.row, res.data, true);
  }
};
</script>
<style lang="scss" scoped>
.v-editor-track {
  height: 100%;
  overflow: hidden;
  > .img-btn {
    display: flex;
    align-items: center;
  }
  .track-texts {
    display: grid;
    grid-template-columns: 1fr 1fr;
    padding: 4px 8px;
    > div {
      text-overflow: ellipsis;
      white-space: nowrap;
      line-height: 16px;
    }
  }
}
</style>
